package br.senac.arqpad.pizzaria.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import br.senac.arqpad.pizzaria.model.ClasseComId;
import br.senac.arqpad.pizzaria.model.Repository;

public class DAOHibernate<T extends ClasseComId> implements Repository<T>  {

	private SessionFactory fabrica;
	private Class<T> tipoItem;
		
	@SuppressWarnings("deprecation")
	public DAOHibernate(Class<T> tipoItem) {
		super();
		this.tipoItem = tipoItem;
		AnnotationConfiguration configuration = new AnnotationConfiguration();
		configuration.configure("hibernate.cfg.xml");
		fabrica = configuration.buildSessionFactory();
	}

	@Override
	public List<T> getLista() {
		return listarTodos();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> listarTodos() {
	
		try			
		{
			
			List<T> lista = null;
			String sql = "from " + tipoItem.getCanonicalName();
			Session sessao = fabrica.openSession();
			Transaction transacao = sessao.beginTransaction();
			lista = (List<T>) sessao.createQuery(sql).list();
			transacao.commit();
			sessao.close();
			return lista;
	
		}
		catch(Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public boolean incluir(T item) {
				
		try {
	
			Session sessao = fabrica.openSession();
			Transaction transacao = sessao.beginTransaction();
			sessao.save(item);
			transacao.commit();
			sessao.close();
	
			return true;
		
		}			
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public boolean atualizar(T item) {
		
		
		try {
	
			Session sessao = fabrica.openSession();
			Transaction transacao = sessao.beginTransaction();
			sessao.update(item);
			transacao.commit();
			sessao.close();
			
			return true;
		
		}			
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


	@Override
	public boolean excluir(T item) {
				
		try {
	
			Session sessao = fabrica.openSession();
			Transaction transacao = sessao.beginTransaction();
			sessao.delete(item);
			transacao.commit();
			sessao.close();
			return true;
		
		}			
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public T obter(ClasseComId itemProcurado) {
	
		try			
		{
			
			T item=null;
			Session sessao = fabrica.openSession();
			Transaction transacao = sessao.beginTransaction();
			item = (T) sessao.get(tipoItem,itemProcurado.getId());
			transacao.commit();
			sessao.close();
	
			// Retorna a lista
			return item;		
		}
		catch(Exception e) {
			throw new RuntimeException(e.getMessage());
		}	
	}
	
}